package bupt.party.online.action;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import bupt.party.online.model.Admin;
import bupt.party.online.model.Student;
import bupt.party.online.service.IAdminService;
import bupt.party.online.service.IBranchService;
import bupt.party.online.service.IStudentService;
import bupt.party.online.util.DateUtil;
import bupt.party.online.util.SessionConstants;

public class LoginAction extends ActionSupport implements ServletRequestAware, ServletResponseAware{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	//验证发生错误的时候，返回给前台界面的提示信息。
	private String result="";
	//用户的身份
	private String userstatus="0";//0为游客 ；1为学生；   2为管理员
	//登录的用户名,
	private String userid;
	//登录的密码
	private String password;
	//验证码
	private String yanzhengma;
	//保存登录前的action
	private String actionName="";
	
	private HttpServletRequest request;
    private HttpServletResponse response; 
    
	private IStudentService studentService;
	private IAdminService adminService;
	private IBranchService branchService;
	
	private String categoryId;
	private String videopath;
	
	public String getCategoryId() {
		return categoryId;
	}

	public void setCategoryId(String categoryId) {
		this.categoryId = categoryId;
	}

	public String getVideopath() {
		return videopath;
	}

	public void setVideopath(String videopath) {
		this.videopath = videopath;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	
	
	public IStudentService getStudentService() {
		return studentService;
	}


	public void setStudentService(IStudentService studentService) {
		this.studentService = studentService;
	}




	public IAdminService getAdminService() {
		return adminService;
	}


	public void setAdminService(IAdminService adminService) {
		this.adminService = adminService;
	}




	public IBranchService getBranchService() {
		return branchService;
	}

	public void setBranchService(IBranchService branchService) {
		this.branchService = branchService;
	}

	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}


	public String getUserstatus() {
		return userstatus;
	}

	public void setUserstatus(String userstatus) {
		this.userstatus = userstatus;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getYanzhengma() {
		return yanzhengma;
	}

	public void setYanzhengma(String yanzhengma) {
		this.yanzhengma = yanzhengma;
	}
	
	
	
	public String getActionName() {
		return actionName;
	}

	public void setActionName(String actionName) {
		this.actionName = actionName;
	}

	public String execute(){
		return "admin";
	}
	
	/*登录验证方法*/
	public String login(){
	    HttpSession session = request.getSession();
		//获取HttpSession中的yanzhengma属性
		String ver2 = (String)session.getAttribute("yanzhengma");
		
		//防止sql注入漏洞
		if(password!=null){
			password = password.replace("'", " ");
		}
		
		
		//首先验证一下验证码是不是正确
		if (yanzhengma==null||(!(yanzhengma.toLowerCase()).equals(ver2))){
			//验证码错误
			result = "验证码错误，请重新输入!";
			return "login";
		}else{
		
			
		//学生登录
		if(userstatus.equals("1")){
	
			//学生用户登录验证
			Student student = studentService.findStudentByUserIdAndPassword(userid, password);
			if(student==null){
				//非法学生用户
				result = "用户名或密码输入错误，请重新输入!";
				return "login";
			}else{
				//合法的学生用户
				
				int branchId = student.getStudentBranchId();
		    	String branchName = branchService.getBranchName(branchId);
		    	request.setAttribute("branchName", branchName);
				
		    	//学生的级别也放到session中。。。
				session.setAttribute(SessionConstants.LEVEL, student.getAdminLevel());
				
				//将学生的个人信息返给界面。
				request.setAttribute("user", student);
				session.setAttribute(SessionConstants.SESSION_USER, student);
				//首先获得上一次的登录时间 和 IP，然后才保存本次的登录时间。（防止覆盖）
				String latestLoginTime = DateUtil.timestamp2Str(student.getStudentLatestLoginTime());
				String lalestLoginIp =student.getStudentLatestLoginIp();
				
				//保存本次登录时间、登录IP
				Timestamp loginTime = new Timestamp(System.currentTimeMillis());
				String loginIp = request.getRemoteAddr();
				student.setStudentLatestLoginTime(loginTime);
				student.setStudentLatestLoginIp(loginIp);
				studentService.saveOrUpdateStudent(student);
				
				session.setAttribute("lalestLoginTime", latestLoginTime);
				session.setAttribute("lalestLoginIp", lalestLoginIp);
				
				Map appMap = ServletActionContext.getContext().getApplication();
				Map sessionMap = (Map)appMap.get("sessionMap");
				if(sessionMap==null){
					sessionMap = new HashMap();
					appMap.put("sessionMap", sessionMap);
				}
				
				String ip = request.getRemoteAddr();
//				session.setMaxInactiveInterval(720);//12分钟
				sessionMap.put(student.getStudentNo(), session);
				
				request.setAttribute("sessionCount", this.sessionCount());
				
				//在跳转之前先判断一下之前登录的actionName
				
				actionName = (String) session.getAttribute("actionName");
				if(!"".equals(actionName)){
					
					if("VideoAction_playVideo.action".equals(actionName) && videopath!=null && !"".equals(videopath)){//播放视频
						return "redirectPlayVideo";
					}else if("VideoAction_playVideo.action".equals(actionName) && (videopath==null || "".equals(videopath))){
						return "home";
					}else
						return "redirect";
				}
				
				return "home";
			}
			
		}else{//管理员用户登录验证
			Admin admin = adminService.findAdminByUserIdAndPassword(userid, password);
			if(admin==null){
				//非法管理员
				result = "用户名或密码输入错误，请重新输入!";
				return "login";
			}else{
				//合法的管理员
				request.setAttribute("user", admin);
				session.setAttribute(SessionConstants.SESSION_USER, admin);
				
				//首先获得上一次的登录时间 和 IP，然后才保存本次的登录时间。（防止覆盖）
				String latestLoginTime = DateUtil.timestamp2Str(admin.getAdminLatestLoginTime());
				String lalestLoginIp =admin.getAdminLatestLoginIp();
				
				//保存本次登录时间、登录IP
				Timestamp loginTime = new Timestamp(System.currentTimeMillis());
				String loginIp = request.getRemoteAddr();
				admin.setAdminLatestLoginTime(loginTime);
				admin.setAdminLatestLoginIp(loginIp);
				adminService.saveOrUpdateAdmin(admin);
				
				session.setAttribute("lalestLoginTime", latestLoginTime);
				session.setAttribute("lalestLoginIp", lalestLoginIp);
				
				
				//管理员登录成功之后，将管理员的级别放入session(1,2,3三个级别)
				session.setAttribute(SessionConstants.LEVEL, admin.getAdminLevel());
				
				return "admin";
			}
		}
		}
		
	}
	
	
	public String loginUI(){
		return "loginUI";
	}
	
	
	public int sessionCount() {
		Map appMap = ServletActionContext.getContext().getApplication();
		Map sessionMap = (Map) appMap.get("sessionMap");
		if (sessionMap == null) {
			return 0;
		}
		
		return sessionMap.keySet().size();
	}

}
